<template>
    <div class="styleImport">
        <el-button @click="handleClick" v-show="isImport" type="primary">{{btnName}}<i class="el-icon-upload el-icon--right"></i></el-button>
        <input type="file" class="el-upload__input" ref="upload" :accept="SheetJSFT" @change="changeFile" />
        <el-button @click="handleDownload" v-show="isDownload" type="primary">模板下载<i class="el-icon-download el-icon--right"></i></el-button>
    </div>
</template>

<script>
    const X = require('xlsx')

    import {
        getExcelTemplates
    } from '@/api/excel/index'
    import {
        exportExcel
    } from '@/utils/excel-export'
    export default {
        props: {
            btnName: {
                default: 'excel导入'
            },
            code: {
                type: String,
                required: true
            },
            isImport:{
                type:Boolean,
                default:true
            },
            isDownload:{
                type:Boolean,
                default:true
            },
            isYanIn : {
                type:Boolean,
                default:false
            }
        },
        computed: {
            charTrans() {
                let map = new Map()
                this.mapping.forEach(item => {
                    map.set(item.chineseTitle, item.englishTitle)
                })
                return map
            },
            verifyField() {
                let map = new Map()
                this.mapping.forEach(item => {
                    map.set(item.englishTitle, item)
                })
                return map
            }
        },
        data() {
            return {
                SheetJSFT: ['xlsx', 'xls'].map(function (x) {
                    return '.' + x
                }).join(','),
                data: [],
                mapping: [],
                errorInfos: [],
                header:0,
            }
        },
        mounted() {
            this.loadExcelTemplate()
        },
        methods: {
            loadExcelTemplate() {
                getExcelTemplates({
                    search_EQ_code: this.code
                }).then(reponse => {
                    this.mapping = reponse.data.aaData[0].excelModelRules
                    // this.header = reponse.data.aaData[0].startLine
                    this.header = 0
                })
            },
            handleClick() {
                this.$refs.upload.click()
            },
            changeFile(evt) {
                const files = evt.target.files
                if (files && files[0]) this.analysisExcel(files[0])
                this.$refs.upload.value = ''
            },
            analysisExcel(file) {
                const self=this
                const reader = new FileReader()
                reader.onload = (e) => {
                    const bstr = e.target.result
                    const wb = X.read(bstr, {
                        type: 'binary'
                    }) // 读取类型为文件类型的字节流
                    const wsname = wb.SheetNames[0] // 获取第一个工作薄名称
                    const ws = wb.Sheets[wsname] // 通过名称获取工作薄
                    const data = X.utils.sheet_to_json(ws, {
                        defval: '',
                        header:self.header
                    }) // header: 参数为1时按行读取,0时第一行为键值读取 defval:使用空字符串替代未填写数据
                    this.data = data
                    if (this.isYanIn){
                        this.generateDataByYanIn()
                    } else {
                        this.generateData()
                    }
                }
                reader.readAsBinaryString(file)
            },
            generateData() {
                let uploadData = []
                this.errorInfos = []
                let vue = this
                this.data.forEach((item, index) => {
                    let waitPush = {}
                    for (let key in item) {
                        let code = vue.charTrans.get(key)
                        waitPush[code] = vue.verify(item[key], vue.verifyField.get(code), index)
                    }
                    uploadData.push(waitPush)
                })
                if (this.errorInfos.length > 0) {
                    let strError = ''
                    this.errorInfos.forEach(errorInfo => {
                        strError += `<strong>${errorInfo}</strong>`
                    })
                    this.$notify.error({
                        title: '上传excel失败',
                        dangerouslyUseHTMLString: true,
                        message: strError,
                        duration: 0
                    })
                } else {
                    this.$emit('getUploadData', uploadData)
                }
            },
            generateDataByYanIn() {
                this.$emit('getUploadData', this.data)
            },
            verify(val, filed, index) {
                if (filed === undefined) {
                    this.$notify.error({
                        title: '上传excel失败',
                        message: '请选择对应模板上传',
                        duration: 0
                    })
                }
                if (filed.isMust) {
                    if (!val) {
                        this.errorInfos.push(`${filed.chineseTitle}为必填选项!第${index + 1}行未填写!`)
                    } else {

                    }
                }
                return val
                // if (rule.type) {
                //   if (rule.type === 'Int') {
                //     parseInt(val)
                //   } else if (rule.type === 'Float') {
                //     return parseFloat(val)
                //   } else {
                //     return val
                //   }
                // } else {
                // }
            },
            // 模板下载
            handleDownload(){
                getExcelTemplates({
                    search_EQ_code: this.code
                }).then(reponse => {
                    this.handleExportExcel(reponse.data.aaData[0])
                })
            },
            handleExportExcel (info) {
                let cols = []
                info.excelModelRules.forEach(item => {
                    cols.push(item.chineseTitle)
                })
                exportExcel(info.name, cols, [])

                // dolNum(info.id).then(res => {
                //   this.loadData()
                // })
            },
        }
    }

</script>

<style lang="scss" scoped>
    .styleImport {
        display: inline-block;
    }

</style>
